package com.hui.platform.falseworkapi.common.core.vo;


import com.alibaba.fastjson.annotation.JSONField;
import com.hui.platform.falseworkapi.common.core.constant.ResultCodeEnum;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.AccessLevel;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;

import java.io.Serializable;

/**
 * 通用Controller层返回结果信息类--注意：只能在controller层使用
 *
 * @author Peng
 * @date 2019/10/23
 */
@ApiModel(value = "结果对象模型")
@Data
@AllArgsConstructor(access = AccessLevel.PRIVATE)
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public final class CommonResult<T> implements Serializable {

    private static final long serialVersionUID = 1L;

    @JSONField(ordinal = 1)
    @ApiModelProperty(value = "是否成功情况", position = 1)
    private boolean success;

    @JSONField(ordinal = 2)
    @ApiModelProperty(value = "结果类型编码", position = 2)
    private long code;

    @JSONField(ordinal = 3)
    @ApiModelProperty(value = "结果类型信息", position = 3)
    private String message;

    @JSONField(ordinal = 4)
    @ApiModelProperty(value = "成功数据信息", position = 4)
    private T data;

    /**
     * 获取结果  ---逻辑处理: 成功、失败、国际化消息
     *
     * @param codeEnum      结果码枚举
     * @param messageSource 国际化消息器
     * @param customMsg     自定义消息
     * @param data          数据
     * @return CommonResult对象
     */
    public static <T> CommonResult<T> build(ResultCodeEnum codeEnum, MessageSource messageSource, String customMsg, T data) {
        //2xxx开头代表成功
        boolean success = String.valueOf(codeEnum.getCode()).startsWith("2");
        long code = codeEnum.getCode();
        //消息
        String message;
        if (customMsg == null || "".equals(customMsg)) {
            //默认采用ResultCodeEnum默认消息
            message = codeEnum.getI18nString(messageSource);
        } else {
            //自定义消息
            if (messageSource != null) {
                message = messageSource.getMessage(customMsg, null, customMsg, LocaleContextHolder.getLocale());
            } else {
                message = customMsg;
            }
        }
        return new CommonResult<>(success, code, message, data);
    }

}
